﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class StockOutNoteDetailOutManage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (Request.QueryString["StockOutNoteID"] != null)
                {
                    if (mk.IsNumber(Request.QueryString["StockOutNoteID"].ToString()))
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblStockOutNoteID.Text = Request.QueryString["StockOutNoteID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }

                //绑定页面基本数据
                this.BindData();
            }
        }
        /// </summary>
        private void BindData()
        {
          var bllHeader = mk.l.Sales_StockOutNoteHeader.ToList();
          Sales_StockOutNoteHeader mHeader = bllHeader.Where(h=>h.StockOutNoteID==int.Parse(this.lblStockOutNoteID.Text)).FirstOrDefault();
            if (mHeader != null)
            {
                Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                //设置根部门ID
                var bllDept = mk.l.Accounts_Department.ToList();
                 this.lblRootDepartmentID.Text = bllDept.Where(j=>j.ClassID==(int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();
                if (int.Parse(this.lblRootDepartmentID.Text) == mHeader.RootDepartmentID)
                {
                    if (mHeader.Status != "1")
                    {
                        //设置入库经办人
                        this.lblInventoryManager.Text = currentUser.UserName;
                        //显示厂家名称
                        //UART.BLL.Sales.Manufacturer bllM = new UART.BLL.Sales.Manufacturer();
                        //UART.Model.Sales.Manufacturer mM = bllM.Where(h=>h.mHeader.ManufacturerID);
                        //this.lblManufacturerName.Text = mM.ManufacturerName;
                        this.lblStockOutNoteNumber.Text = mHeader.StockOutNoteNumber;
                        this.lblDateStockOut.Text = mHeader.DateStockOut.ToString();
                        //显示出库经办人
                        this.lblManagerTrueName.Text = currentUser.TrueName;
                        //显示出库单经办人
                        var bllUser = mk.l.Accounts_Users.ToList();
                    Accounts_Users mUser = bllUser.Where(h=>h.UserName==mHeader.Manager).FirstOrDefault();
                        this.lblHeaderManagerTrueName.Text = mUser.TrueName;
                        //this.lblSubTotal.Text = mHeader.SubTotal.ToString("c");
                        this.BindStockOutNoteDetail();
                        //绑定仓库下拉列表框
                        this.BindLocationID(ddlLocationID);
                        //不能修改初始添加和已经出库的订单
                        if (mHeader.Status != "2")
                        {
                            this.btnOK.Enabled = false;
                            this.btnOK.Visible = false;
                            this.btnSelectOutInventory.Enabled = false;
                            this.btnSelectOutInventory.Visible = false;
                            this.btnClose.Enabled = true;
                            this.btnClose.Visible = true;
                            this.myGridView.Columns[6].Visible = false;
                        }
                    }
                    else
                    {
                       mk.Alert("此出库单未提交！");
                    }
                }
                else
                {
                   mk.Alert("只能操作本店的订单！");
                }
            }
            else
            {
               mk.Alert("参数错误！");
            }
        }


        /// <summary>
        /// Binds the stock out note detail.绑定出库明细列表
        /// </summary>
        private void BindStockOutNoteDetail()
        {
          var bll = mk.l.Sales_StockOutNoteDetailandSales_Material.ToList();
           var ds = bll.Where(y=>y.StockOutNoteID.ToString()==this.lblStockOutNoteID.Text).ToList();
            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
        }

        /// <summary>
        /// Handles the RowEditing event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.myGridView.EditIndex = e.NewEditIndex;
            this.BindStockOutNoteDetail();
        }

        /// <summary>
        /// Handles the RowCancelingEdit event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.myGridView.EditIndex = -1;
            this.BindStockOutNoteDetail();
        }

        /// <summary>
        /// Handles the RowDataBound event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
            var bll = mk.l.Sales_StockOutNoteDetail.ToList();
            Sales_StockOutNoteDetail m = bll.Where(h=>h.DetailID==int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["DetailID"].ToString())).FirstOrDefault();

                //显示是否出库 仓库信息
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    Label lblLocation = (Label)(e.Row.FindControl("lblLocation"));
                    Label lblStatusStockOut = (Label)(e.Row.FindControl("lblStatusStockOut"));

                    if (lblLocation != null)
                    {
                        if (m.LocationID == 0)
                        {
                            lblLocation.Text = "未出库";
                        }
                        else
                        {
                          var bllLocation = mk.l.Sales_Location.ToList();
                        Sales_Location mLocation = bllLocation.Where(h=>h.LocationID==m.LocationID).FirstOrDefault();
                            lblLocation.Text = mLocation.Name;
                        }
                    }

                    if (lblStatusStockOut != null)
                    {
                        if (m.StatusStockOut == "0")
                        {
                            lblStatusStockOut.Text = "未出库";
                            lblStatusStockOut.ForeColor = System.Drawing.Color.Red;
                        }
                        else
                        {
                            lblStatusStockOut.Text = "已出库";
                            lblStatusStockOut.ForeColor = System.Drawing.Color.Green;
                        }
                    }

                }
                if (e.Row.RowState == DataControlRowState.Edit || (int)e.Row.RowState == 5)
                {
                    DropDownList ddlLocationID = (DropDownList)(e.Row.FindControl("ddlLocationID"));
                    if (ddlLocationID != null)
                    {
                        this.BindLocationID(ddlLocationID);
                        if (m.LocationID != 0)
                        {
                            ddlLocationID.Items.FindByValue(m.LocationID.ToString()).Selected = true;
                        }
                    }
                }

            }
        }

        /// <summary>
        /// Binds the location ID.绑定指定的仓库下拉列表框
        /// </summary>
        /// <param name="ddlLocationID">The DDL location ID.</param>
        private void BindLocationID(DropDownList ddlLocationID)
        {
           var bll = mk.l.Sales_Location.ToList();
           var ds = bll.Where(h => h.RootDepartmentID.ToString() == this.lblRootDepartmentID.Text).ToList();
                
            ddlLocationID.DataSource = ds;
            ddlLocationID.DataTextField = "Name";
            ddlLocationID.DataValueField = "LocationID";
            ddlLocationID.DataBind();
        }

        /// <summary>
        /// Handles the RowUpdating event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (this.IsValid)
            {
                this.lblMsg.Text = "";
                //得到定义了仓库列表的DropDownList控件
                DropDownList ddlLocationID = 
                    (DropDownList)(this.myGridView.Rows
                    [e.RowIndex].FindControl("ddlLocationID"));
                //得到出库单明细ID值
                int intDetailID = int.Parse(this.myGridView.DataKeys
                    [e.RowIndex].Values["DetailID"].ToString());
                //从DropDownList控件中获取仓库ID
                int intLocationID = int.Parse(ddlLocationID.SelectedValue);
                //使用出库明细逻辑类得到出库单实例
               var bll = 
                    mk.l.Sales_StockOutNoteDetail.ToList();
             Sales_StockOutNoteDetail m = bll.Where(h=>h.DetailID==intDetailID).FirstOrDefault();
                //根据出库单的状态，已经出库的不能再出库
                if (m.StatusStockOut == "0")
                {
                    int intMaterialID =int.Parse( m.MaterialID.ToString()); //得到材料编号
                    decimal decQuantity =Convert.ToDecimal( m.Quantity.ToString()); //出库数量
                    //保存原仓库ID
                    int intOldLocationID = int.Parse(m.LocationID.ToString());
                    //材料出库
                    m.StatusStockOut = "1";
                    m.InventoryManager = 
                        this.lblInventoryManager.Text;
                    m.LocationID = intLocationID;
                    m.DateStockOut = System.DateTime.Now;
                    m.ModifiedDate = System.DateTime.Now;
                    //这里要用事务，更新记录，同时更新订货单概况的信息
                    try
                    {
                       mk.l.SubmitChanges(); 
                            var bllHeader=mk.l.Sales_StockOutNoteDetail.ToList();//更新出库记录
                  var bllHeader1 = 
                           mk.l.Sales_StockOutNoteHeader.ToList();
                        //如果此订货单已全部出库，设置订货单出库状态
                        if (bllHeader.Where(h=>h.StockOutNoteID==(int.Parse(this.lblStockOutNoteID.Text))).Count()==bllHeader.Where(h=>h.StockOutNoteID==(int.Parse(this.lblStockOutNoteID.Text))&h.StatusStockOut=="1").Count())
                        {
                        Sales_StockOutNoteHeader mHeader = 
                                bllHeader1.Where(h=>h.StockOutNoteID==int.Parse(this.lblStockOutNoteID.Text)).FirstOrDefault();
                            //更新用料单的出库状态
                        var bllNeedHeader =
                             mk.l.Sales_NeedMaterialHeader.ToList();
                        var ma = bllNeedHeader.Where(y => y.NeedMaterialID.ToString() == mHeader.NeedMaterialID.ToString()).ToList();
                            foreach(var mab in ma)
                            {
 mab.StatusStockOut="2";
                                mk.l.SubmitChanges();
                            };
                               
                            mHeader.Status = "3";
                            mHeader.ModifiedDate = System.DateTime.Now;
                          //  bllHeader.Update(mHeader);  //更新材料出库状态
                            mk.l.SubmitChanges();
                        }
                        //在库存清单中修改库存
                    var bllInventory =
                           mk.l.Sales_MaterialInventory.ToList();
                        //先判断是否修改了出库仓库，如果修改了，
                        //则以前的仓库要入库，再向新仓库出库
                        if (intOldLocationID != 0 && intOldLocationID != intLocationID)
                        {
                            mk.StockIn(intMaterialID, decQuantity, 
                                intOldLocationID, 
                                int.Parse(this.lblRootDepartmentID.Text));
                        }
                      mk.StockOut(intMaterialID, decQuantity, 
                            intLocationID, 
                            int.Parse(this.lblRootDepartmentID.Text));
                      //  ContextUtil.SetComplete();     //提交事务
                    }
                    catch (Exception ex)
                    {
                        //撤销事务
                      //  ContextUtil.SetAbort();
                        this.lblMsg.Text = "出库错误！错误信息：" + ex.Message;
                    }
                }
                this.myGridView.EditIndex = -1;
                this.BindStockOutNoteDetail();      //重新绑定出库数据
            }
        }

        /// <summary>
        /// Handles the Click event of the btnSelectOutInventory control.所选明细全部出库
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnSelectOutInventory_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
             var bllHeader = mk.l.Sales_StockOutNoteHeader.ToList();
              Sales_StockOutNoteHeader mHeader = bllHeader.Where(h=>h.StockOutNoteID==int.Parse(this.lblStockOutNoteID.Text)).FirstOrDefault();
                if (mHeader.Status == "2")
                {
                    string strArrDetailID = string.Empty;
                    //遍历所有的 chkSelect 
                    foreach (GridViewRow gr in this.myGridView.Rows)
                    {
                        CheckBox chk = (CheckBox)gr.FindControl("chkSelect");
                        if (chk.Checked)
                        {
                            strArrDetailID = strArrDetailID + this.myGridView.DataKeys[gr.RowIndex].Values["DetailID"].ToString() + ",";
                        }
                    }
                    if (strArrDetailID != string.Empty)
                    {
                        strArrDetailID = strArrDetailID.Substring(0, strArrDetailID.Length - 1);
                        string[] arrDetailID = strArrDetailID.Split(',');
                        int intLocationID = int.Parse(this.ddlLocationID.SelectedValue);
                        //这里要用事务，更新记录，同时更新订货单概况的信息
                        try
                        {
                            for (int i = 0; i < arrDetailID.Length; i++)
                            {
                                int intDetailID = int.Parse(arrDetailID[i]);
                            var bll = mk.l.Sales_StockOutNoteDetail.ToList();
                               Sales_StockOutNoteDetail m = bll.Where(h=>h.DetailID==intDetailID).FirstOrDefault();
                                //这里要判断一下 如果已经出库 就不处理了
                                if (m.StatusStockOut == "0")
                                {
                                    int intMaterialID = int.Parse(m.MaterialID.ToString()); //得到材料编号
                                    decimal decQuantity = Convert.ToDecimal(m.Quantity.ToString()); //出库数量
                                    //保存原仓库ID
                                    int intOldLocationID = int.Parse(m.LocationID.ToString());
                               
                                    //材料出库
                                    m.StatusStockOut = "1";
                                    m.InventoryManager = this.lblInventoryManager.Text;
                                    m.LocationID = intLocationID;
                                    m.DateStockOut = System.DateTime.Now;
                                    m.ModifiedDate = System.DateTime.Now;

                                    mk.l.SubmitChanges();
                                    var bllHeader1 = mk.l.Sales_StockOutNoteDetail.ToList();
                                    //如果此出库单已全部出库，设置出库单出库状态
                                    if (bllHeader1.Where(h => h.StockOutNoteID == (int.Parse(this.lblStockOutNoteID.Text))).Count() == bllHeader1.Where(h => h.StockOutNoteID == (int.Parse(this.lblStockOutNoteID.Text)) & h.StatusStockOut == "1").Count())
                                    {
                                        //更新用料单的出库状态
                                       var bllNeedHeader =mk.l.Sales_NeedMaterialHeader.ToList();
                                       var ma = bllNeedHeader.Where(y => y.NeedMaterialID.ToString() == mHeader.NeedMaterialID.ToString()).ToList();
                            foreach(var mab in ma)
                            {
                         mab.StatusStockOut="2";
                                mk.l.SubmitChanges();
                            };

                                        mHeader.Status = "3";
                                        mHeader.ModifiedDate = System.DateTime.Now;
                                      //  bllHeader.Update(mHeader);
                                    }
                                    //材料出库 修改库存
                                 //   UART.BLL.Sales.MaterialInventory bllInventory = new UART.BLL.Sales.MaterialInventory();
                                    //先判断是否修改了出库仓库，如果修改了，则以前的仓库要入库，再向新仓库出库
                                    if (intOldLocationID != 0 && intOldLocationID != intLocationID)
                                    {
                                        mk.StockIn(intMaterialID, decQuantity, intOldLocationID, int.Parse(this.lblRootDepartmentID.Text));
                                    }
                                   mk.StockOut(intMaterialID, decQuantity, intLocationID, int.Parse(this.lblRootDepartmentID.Text));
                                    //this.myGridView.EditIndex = -1;
                                }
                            }
                            
                            this.btnSelectOutInventory.Enabled = false;
                            this.lblMsg.Text = "出库成功！";
                            //提交事务
                         //   ContextUtil.SetComplete();
                        }
                        catch (Exception ex)
                        {
                            //撤销事务
                        //    ContextUtil.SetAbort();
                            this.lblMsg.Text = "出库错误！错误信息：" + ex.Message;
                        }

                    }
                }
                else
                {
                    this.lblMsg.Text = "出库错误！此出库单已经出库";
                }
                this.BindStockOutNoteDetail();
            }
        }



    }
}
